package com.example.jx;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;

/**
 * 处理图片的类
 * 
 * @author Administrator
 *
 */
public class PictureUtils {

	/**
	 * drawable 转 bitmap
	 * 
	 * @param drawable
	 * @return
	 */
	public  static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();

		Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.RGB_565
				: Bitmap.Config.ARGB_8888;
		Bitmap bitmap = Bitmap.createBitmap(width, height, config);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);
		return bitmap;
	}

	/**
	 * bitmap 转 drawable
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Drawable bitmapToDrawable(Bitmap bitmap) {
		Drawable drawable = new BitmapDrawable(bitmap);
		return drawable;
	}

	/**
	 * inputstream 转 Bitmap
	 * 
	 * @param is
	 * @return
	 */
	private static Bitmap inputstreamToBitmap(InputStream is) {
		Bitmap bitmap = BitmapFactory.decodeStream(is);
		return bitmap;
	}

	/**
	 * 保存bitmap到本地
	 * 
	 * @param fileName
	 * @param bitmap
	 * @return
	 */
	public static boolean saveBitmap(Bitmap bitmap, String fileName) {
		File file = new File(Environment.getExternalStorageDirectory(),
				fileName);
		OutputStream osOutputStream;
		try {
			osOutputStream = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG, 100, osOutputStream);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * bitmap的缩放
	 * 
	 * @param bitmap
	 * @param zoom
	 * @return
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, float zoom) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		matrix.setScale(zoom, zoom);
		Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return bitmap2;
	}
	
	
	

}
